package com.wanchuang.qhbb.web.ui;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.zxing.client.result.VINParsedResult;
import com.wanchuang.qhbb.MainActivity;
import com.wanchuang.qhbb.R;
import com.wanchuang.qhbb.base.BaseActivity;
import com.wanchuang.qhbb.base.MainApplication;
import com.wanchuang.qhbb.dialog.DialogUtils;
import com.wanchuang.qhbb.help.ImageHelper;
import com.wanchuang.qhbb.help.PermissionHelper;
import com.wanchuang.qhbb.help.UserHelper;
import com.wanchuang.qhbb.module.login.LoginActivity;
import com.wanchuang.qhbb.module.login.TakeIdCardActivity;
import com.wanchuang.qhbb.net.Apis;
import com.wanchuang.qhbb.net.NetworkManager;
import com.wanchuang.qhbb.net.interfaces.OnRequestCallBack;
import com.wanchuang.qhbb.net.interfaces.OnUpLoadCallBack;
import com.wanchuang.qhbb.proto.MemberOuterClass;
import com.wanchuang.qhbb.utils.CacheUtil;
import com.wanchuang.qhbb.utils.GsonUtils;
import com.wanchuang.qhbb.utils.ImageUtil;
import com.wanchuang.qhbb.utils.LogUtil;
import com.wanchuang.qhbb.utils.SaveViewToImageUtil;
import com.wanchuang.qhbb.utils.StatusBarUtil;
import com.wanchuang.qhbb.web.inteface.JavaScriptInterface;
import com.wanchuang.qhbb.web.manager.MyChromeClient;
import com.wanchuang.qhbb.web.manager.WebViewClientUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.jessyan.autosize.utils.LogUtils;

public class WebViewActivity extends BaseActivity implements WebViewClientUtil.WebClientLoadListener,
        MyChromeClient.ProgressChangedListener, MyChromeClient.ReceivedTitleListener {


    //全局声明，用于记录选择图片返回的地址值
    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private static final String KEY_WEBURL = "KEY_WEBURL";
    public static final int BACK = 0x1fe;
    public static final int GOTOCARDPRINT = 0x2fe;
    public static final int GOTOCAPTURE = 0x3fe;
    public static final int LOGIN = 0x4fe;
    public static final int LOGIN_OUT = 0x5fe;
    public static final int GOTOMAIN = 0x6fe;
    public static final int TAKEPHOTO = 0x7fe;
    public static final int JUMPTO = 0x8fe;
    public static final int DOWNLOAD = 0x9fe;
    public static final int SAVE = 0x1ff;
    public static final int TAKEPHOTOIDCARD = 0xffe;

    //文件选择所需
    public final static int FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 = 2;
    public final static int FILE_CHOOSER_RESULT_CODE = 1;// 表单的结果回调


    @BindView(R.id.webView)
    WebView webView;

    @BindView(R.id.prograssBar)
    ProgressBar prograssBar;

    @BindView(R.id.rv_message)
    RelativeLayout rvMessage;


    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.back_iv)
    ImageView ivback;

    @BindView(R.id.rv_title)
    RelativeLayout rvTitle;


    private MyChromeClient myChromeClient;
    private String url;
    public String methodName = "";

    private Handler jsInterfaceHandler;


    /**
     * 不带参数的地址
     *
     * @param context
     * @param url
     */
    public static void startActivity(Context context, String url) {
        if (context == null) return;
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(KEY_WEBURL, url);
        context.startActivity(intent);
    }

    public static Intent startIntentActivity(Context context, String url) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(KEY_WEBURL, url);
        return intent;
    }

    /**
     * 不带参数的地址
     *
     * @param context
     * @param url
     */
    public static void startActivity(Context context, String url, boolean only) {
        if (context == null) return;
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(KEY_WEBURL, url);
        intent.putExtra("only", only);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        StatusBarUtil.setWhiteStatusBar(this);
        MainApplication.addWebActivity(this);
        ButterKnife.bind(this);
        initWebView();

    }

    //同步cookie
    private void syncCookie(Context context, String url) {
        try {
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeAllCookie();
            cookieManager.setCookie(url, "key=" + UserHelper.getCurrentToken());
            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
                LogUtil.d("Wang", "设置Cookie url=" + url + " ;   cookie=" + newCookie);
            }
        } catch (Exception e) {
            LogUtil.e("Wang: webView.syncCookie failed", e.toString());
        }
    }


    private void initWebView() {


        jsInterfaceHandler = new JsInterfaceHandler(this, webView, rvMessage);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface(jsInterfaceHandler), "app");
        webView.setWebViewClient(new WebViewClientUtil(this, this));
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setLoadsImagesAutomatically(true);// 加载网页中的图片
        webView.getSettings().setUseWideViewPort(true); //设置使用视图的宽端口
        webView.setWebChromeClient(myChromeClient = new MyChromeClient(this, this, this, webView, null));
        webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        url = getIntent().getStringExtra(KEY_WEBURL);

        if (url.contains("transferApplication")) {
            rvTitle.setVisibility(View.VISIBLE);
            ivback.setOnClickListener(v -> finish());
        }
        if (!url.contains("http")) {
            url = MainApplication.getServiceHost() + getIntent().getStringExtra(KEY_WEBURL);
        }
        if (getIntent().getBooleanExtra("only", true)) {
            loadUrl();
        } else {
            webView.loadUrl(url);
        }

    }

    private void loadUrl() {
        String newUrl;
        //统一拼接可
        if (UserHelper.isLogin()) {
            if (url.contains("?")) {
                newUrl = url + "&key=" + UserHelper.getCurrentToken() + "&isBack=1";
            } else {
                newUrl = url + "?key=" + UserHelper.getCurrentToken() + "&isBack=1";
            }
        } else {
            newUrl = url + "&isBack=true";
        }
        webView.loadUrl(newUrl);
        LogUtil.e("wang", "网页请求地址：" + newUrl);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.destroy();
        }
        MainApplication.removeWebActivity(this);
    }


    public void onResume() {

        super.onResume();


    }

    @Override

    public void onPause() {

        super.onPause();
    }


    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
        switch (requestCode) {
            case FILE_CHOOSER_RESULT_CODE:
                if (null == myChromeClient.getmUploadMessage()) {
                    return;
                }
                myChromeClient.getmUploadMessage().onReceiveValue(result);
                myChromeClient.setmUploadMessage(null);
                break;
            case FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5:
                if (null == myChromeClient.getmUploadMessageForAndroid5())
                    return;
                if (result != null) {
                    myChromeClient.getmUploadMessageForAndroid5().onReceiveValue(new Uri[]{result});
                } else {
                    myChromeClient.getmUploadMessageForAndroid5().onReceiveValue(new Uri[]{});
                }
                myChromeClient.setmUploadMessageForAndroid5(null);
                break;
            case PictureConfig.CHOOSE_REQUEST:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(intent);
                    if (localMedias.size() == 1) {
                        String compressPath = localMedias.get(0).getCompressPath();
                        upLoadImage(compressPath);
                    } else {
                        upLoadMultiImage(localMedias);
                    }
                }
                break;
            case 100:
                if (resultCode == RESULT_OK) {
                    String compressPath = intent.getAction();
                    upLoadImage(compressPath);
                }
                break;

        }
    }

    private void upLoadImage(String compressPath) {
        showProgress();
        ImageHelper.upLoadImage(compressPath, new ImageHelper.OnUpLoadImageCallBack() {
            @Override
            public void onSuccess(String images) throws InvalidProtocolBufferException {
                String[] temp = images.split(",");
                byte[] bytes = new byte[temp.length];
                for (int i = 0; i < temp.length; i++) {
                    bytes[i] = (byte) Integer.parseInt(temp[i]);
                }
                hideProgress();
                webView.loadUrl("javascript:" + methodName + "('" + MemberOuterClass.img_upload.parseFrom(bytes).getImg() + "')");
            }

            @Override
            public void onFail(String error) {
                hideProgress();
                showToast(error);
            }
        });
    }


    private void upLoadMultiImage(List<LocalMedia> localMedias) {
        showProgress();
        NetworkManager.INSTANCE.upLoadMultiFile(localMedias, new OnUpLoadCallBack() {
            @Override
            public void onOk(String response) {
                hideProgress();
                Log.e("javascript", response);
                webView.loadUrl("javascript:" + methodName + "('" + response + "')");
            }

            @Override
            public void onError(int code, String errorMessage) {

            }

            @Override
            public void upProgress(int progress) {

            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (webView.canGoBack() && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            webView.goBack();
            return true;
        }
        if (url.contains("Verification")) {
            DialogUtils.showDefaultDialog(this, "", "确定退出登录?", new DialogUtils.DialogImpl() {
                @Override
                public void onOk() {
                    NetworkManager.INSTANCE.post(Apis.logout, new OnRequestCallBack() {
                        @Override
                        public void onOk(byte[] bytes) {
                        }

                        @Override
                        public void onError(int code, String errorMessage) {
                        }
                    });
                    Intent intent2 = new Intent(WebViewActivity.this, LoginActivity.class);
                    intent2.putExtra("phone", UserHelper.getUser().getMember_mobile());
                    UserHelper.loginOut();
                    startActivity(intent2);
                    finish();
                }
            });
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }


    @Override
    public void loadFinished(String title, boolean isError) {
    }



    /*--------------------------------H5 调用原生--------------------------------*/

    private static class JsInterfaceHandler extends Handler {
        private WeakReference<Activity> weakRefActivity;
        private WebViewActivity context;
        private WebView webViews;
        private RelativeLayout contentLayout;

        public JsInterfaceHandler(WebViewActivity activity, WebView webViews, RelativeLayout contentLayout) {
            this.context = activity;
            this.webViews = webViews;
            this.contentLayout = contentLayout;

            weakRefActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            Activity activity = weakRefActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case BACK:
                        activity.finish();
                        break;
                    case LOGIN:
                        UserHelper.loginOut();
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        break;
                    case GOTOCAPTURE:
                        captureWebView1(context, context.webView);
                        break;
                    case LOGIN_OUT:
                        DialogUtils.showDefaultDialog(context, "", "确定退出登录?", new DialogUtils.DialogImpl() {
                            @Override
                            public void onOk() {
                                NetworkManager.INSTANCE.post(Apis.logout, new OnRequestCallBack() {
                                    @Override
                                    public void onOk(byte[] bytes) {
                                    }

                                    @Override
                                    public void onError(int code, String errorMessage) {
                                    }
                                });
                                Intent intent2 = new Intent(context, LoginActivity.class);
                                intent2.putExtra("phone", UserHelper.getUser().getMember_mobile());
                                UserHelper.loginOut();
                                context.startActivity(intent2);
                                context.finish();
                            }
                        });
                        break;
                    case GOTOMAIN:
                        Intent intent3 = new Intent(context, MainActivity.class);
                        context.startActivity(intent3);
                        context.finish();
                        break;
                    case TAKEPHOTO:
                        String tk_s = (String) msg.obj;
                        String[] tk_strings = tk_s.split(",");
                        context.methodName = tk_strings[0];
                        ImageHelper.showMultiChoose(context, Integer.parseInt(tk_strings[1]));
                        break;
                    case DOWNLOAD:
                        String dl_s = (String) msg.obj;
                        String[] dl_strings = dl_s.split(",");
                        downloadImage(context, dl_strings[0], context.webView, dl_strings[1]);
                        break;
                    case SAVE:
                        String sa_s = (String) msg.obj;
//                        String[] sa_strings = sa_s.split(",");
//                        saveImage(context, sa_strings[0], sa_strings[1], webViews);
                        QrMessageBean qrMessageBean = GsonUtils.jsonToBean(sa_s, QrMessageBean.class);
                        Log.e("message", qrMessageBean.toString());
                        captureWebView2(context, webViews, contentLayout, qrMessageBean);
                        break;

                    case TAKEPHOTOIDCARD:
                        String s = (String) msg.obj;
                        String[] strings = s.split(",");
                        context.methodName = strings[0];
                        List<String> permission = new ArrayList<>();
                        permission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        permission.add(Manifest.permission.CAMERA);
                        permission.add(Manifest.permission.READ_EXTERNAL_STORAGE);
                        PermissionHelper.getInstance().getPermissionGroup(context, new PermissionHelper.PermissionCallBack() {
                            @Override
                            public void onSuccess() {
                                if (strings[1].equals("3")) {
                                    ImageHelper.showImageChoose(context);
                                } else {
                                    Intent intent2 = new Intent(context, TakeIdCardActivity.class);
                                    intent2.setType(strings[1]);
                                    context.startActivityForResult(intent2, 100);
                                }
                            }

                            @Override
                            public void onFail() {
                                Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT).show();
                            }
                        }, permission);
                        break;
                }
            }
        }

    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        //进度显示
        if (newProgress > 80) {
            prograssBar.setVisibility(View.GONE);
        } else {
            prograssBar.setProgress(newProgress);
        }
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        //网页加载完成 这里设置标题
        if (title.contains("http") || title.contains("网页无法打开") || title.contains(".com") || title.contains(".cn")) {
            return;
        }
    }


    /**
     * 对WebView进行截图
     *
     * @param webView
     * @return
     */
    public static void captureWebView1(Context context, WebView webView) {//可执行
        PermissionHelper.getInstance().getPermission((FragmentActivity) context, new PermissionHelper.PermissionCallBack() {
            @Override
            public void onSuccess() {
                Bitmap viewBitmap = SaveViewToImageUtil.getViewBitmap(webView);
                String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + context.getString(R.string.app_name);
                String fileName = System.currentTimeMillis() + ".jpg";
                boolean b = ImageUtil.saveImageToGallery(context, viewBitmap, storePath, fileName);
                if (b) {
                    Toast.makeText(context, "截图保存成功，请在相册查看", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFail() {
                Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }


    public static void downloadImage(Context context, String imageUrl, WebView webView, String methodName) {//可执行
        Glide.with(context).downloadOnly().load(imageUrl).into(new SimpleTarget<File>() {
            @Override
            public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                if (resource != null) {
                    try {
                        //获取到下载得到的图片，进行本地保存
                        String folder = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "download";
                        File appDir = new File(folder, "pictures");
                        if (!appDir.exists()) {
                            appDir.mkdirs();
                        }
                        String[] fileNames = imageUrl.split("/");
                        String fileName = fileNames[fileNames.length - 1];
                        File destFile = new File(appDir, fileName);
                        if (destFile.exists()) {
                            Toast.makeText(context, "图片已存在", Toast.LENGTH_SHORT).show();
                            String path = destFile.getAbsolutePath();
                            webView.loadUrl("javascript:" + methodName + "('" + imageToBase64(path) + "')");
                        } else {
                            boolean status = CacheUtil.copy(resource, destFile);
                            if (status) {
                                CacheUtil.addMediaStore(context, destFile, destFile.getAbsolutePath());
                                Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
                                String path = destFile.getAbsolutePath();
                                webView.loadUrl("javascript:" + methodName + "('" + imageToBase64(path) + "')");
                            } else {
                                Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    } catch (Exception e) {
                        LogUtils.e(e.toString());
                        Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
                    }

                }
            }
        });
    }

    public static void saveImage(Context context, String baseDate, String methodName, WebView webView) {//可执行
        try {
            //获取到下载得到的图片，进行本地保存
            String folder = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "download";
            File appDir = new File(folder, "pictures");
            if (!appDir.exists()) {
                appDir.mkdirs();
            }
            String fileName = System.currentTimeMillis() + ".jpg";
            File destFile = new File(appDir, fileName);
            String path = destFile.getAbsolutePath();
            boolean result = base64ToFile(baseDate, path);
            if (result) {
                webView.loadUrl("javascript:" + methodName + "('" + imageToBase64(path) + "')");
                Toast.makeText(context, "合成成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "合成失败", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            LogUtils.e(e.toString());
            Toast.makeText(context, "合成失败", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 将图片转换成Base64编码的字符串
     */
    public static String imageToBase64(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.NO_CLOSE);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }


    /**
     * 将Base64编码转换为图片
     *
     * @param base64Str
     * @param path
     * @return true
     */
    public static boolean base64ToFile(String base64Str, String path) {
        byte[] data = Base64.decode(base64Str, Base64.NO_WRAP);
        for (int i = 0; i < data.length; i++) {
            if (data[i] < 0) {
                //调整异常数据
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(path);
            os.write(data);
            os.flush();
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    public static void captureWebView2(Context context, WebView webView, RelativeLayout contentView, QrMessageBean messageBean) {
        PermissionHelper.getInstance().getPermission((FragmentActivity) context, new PermissionHelper.PermissionCallBack() {
            @Override
            public void onSuccess() {
                Glide.with(context)
                        .asBitmap()
                        .load(messageBean.getAdvCode())
                        .into(new CustomTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                if (messageBean.getIsAdditional().equals("1")) {  // 需要加载信息数据
                                    contentView.setVisibility(View.VISIBLE);
                                    TextView memberName = contentView.findViewById(R.id.tv_message_title);
                                    memberName.setText(messageBean.getMemberName());
                                    TextView textss = contentView.findViewById(R.id.tv_message_text);
                                    textss.setText(messageBean.getText());
                                    TextView tip = contentView.findViewById(R.id.tv_message_tips);
                                    tip.setText(messageBean.getTip());
                                    ImageView qrView = contentView.findViewById(R.id.iv_message_qr);
                                    Glide.with(context)
                                            .load(messageBean.getQrcodeUrl())
                                            .into(new CustomTarget<Drawable>() {
                                                @Override
                                                public void onResourceReady(@NonNull Drawable drawableResource, @Nullable Transition<? super Drawable> transition) {
                                                    qrView.setImageDrawable(drawableResource);
                                                    String storePath = context.getFilesDir().getAbsolutePath() + File.separator + "截图";
                                                    String fileName = System.currentTimeMillis() + ".png";
                                                    Bitmap viewBitmap = SaveViewToImageUtil.getViewBitmap(contentView);
                                                    float widthScale = (float) resource.getWidth() / (float) viewBitmap.getWidth();
                                                    Matrix matrix = new Matrix();
                                                    matrix.postScale(widthScale, widthScale);  //长和宽放大缩小的比例
                                                    Bitmap resizeBmp = Bitmap.createBitmap(viewBitmap, 0, 0, viewBitmap.getWidth(),
                                                            viewBitmap.getHeight(), matrix, true);
                                                    Bitmap ImageBitmap = Bitmap.createBitmap(resource.getWidth(), resource.getHeight() + resizeBmp.getHeight(),
                                                            resource.getConfig());
                                                    Canvas canvas = new Canvas(ImageBitmap);
                                                    canvas.drawBitmap(resource, new Matrix(), null);
                                                    canvas.drawBitmap(resizeBmp, 0, resource.getHeight(), null);
                                                    boolean b = ImageUtil.saveImageToGallery(context, ImageBitmap, storePath, fileName);
                                                    if (b) {
                                                        Toast.makeText(context, "保存成功，请在相册查看", Toast.LENGTH_SHORT).show();
                                                        webView.loadUrl("javascript:" + messageBean.getSuccess() + "()");
                                                        //获取剪贴板管理器
                                                        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                                        // 创建普通字符型ClipData
                                                        ClipData mClipData = ClipData.newPlainText("Label", messageBean.getCopyText());
                                                        // 将ClipData内容放到系统剪贴板里。
                                                        cm.setPrimaryClip(mClipData);
                                                    } else {
                                                        Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                                        webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                                                    }
                                                }

                                                @Override
                                                public void onLoadCleared(@Nullable Drawable placeholder) {
//                                                    Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                                    webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                                                }
                                            });
                                } else {
                                    String storePath = context.getFilesDir().getAbsolutePath() + File.separator + "截图";
                                    String fileName = System.currentTimeMillis() + ".png";
                                    boolean b = ImageUtil.saveImageToGallery(context, resource, storePath, fileName);
                                    if (b) {
                                        Toast.makeText(context, "保存成功，请在相册查看", Toast.LENGTH_SHORT).show();
                                        webView.loadUrl("javascript:" + messageBean.getSuccess() + "()");
                                        //获取剪贴板管理器
                                        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                        // 创建普通字符型ClipData
                                        ClipData mClipData = ClipData.newPlainText("Label", messageBean.getCopyText());
                                        // 将ClipData内容放到系统剪贴板里。
                                        cm.setPrimaryClip(mClipData);
                                    } else {
                                        Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                        webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                                    }
                                }


                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {
//                                Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
//                                webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                            }
                        });
            }

            @Override
            public void onFail() {
                Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);


    }

}
